package com.lanou.utp.controller;

import com.lanou.utp.entity.LoginUser;
import com.lanou.utp.entity.ValidateDetails;
import com.lanou.utp.service.LoginService;
import com.lanou.utp.entity.ResponseData;
import com.lanou.utp.utils.TokenManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class LoginController {

    @Resource
    private TokenManager tokenManager;

    @Resource
    private LoginService loginService;

    @PostMapping("/wx/login")
    @ResponseBody
    public ResponseData login(HttpServletResponse response,
                              @RequestBody LoginUser user) throws IOException {

        // 获取验证信息
        ValidateDetails validateDetails = loginService.validateUser(user);

        // 如果验证没通过
        if (!validateDetails.getVerified()) {
            return new ResponseData(499, "验证失败, 请检查登录信息");
        }

        // cookie里塞入token
        String token = tokenManager.createLoginToken(validateDetails);
        Cookie cookie = new Cookie("vue_admin_template_token", token);
        cookie.setPath("/");
        response.addCookie(cookie);

        return new ResponseData("ok", token);
    }

    @GetMapping("/logout")
    @ResponseBody
    public ResponseData logout(HttpServletResponse response) {
        Cookie cookie = new Cookie("vue_admin_template_token", null);
        response.addCookie(cookie);
        return new ResponseData("ok");

    }




}
